package org.ns.framework.webmvc.interceptor;

import java.util.Locale;

import org.ns.framework.webmvc.anns.GetLocale;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
/**
 * locale 参数注入
 * 
 * @author zhangxingyu
 *
 */
public class LocaleParameterInjector implements HandlerMethodArgumentResolver {

	@Override
	public boolean supportsParameter(MethodParameter parameter) {

		return parameter.hasParameterAnnotation(GetLocale.class) && parameter.getParameterType() == String.class;
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

		GetLocale getLocale = parameter.getParameterAnnotation(GetLocale.class);
		String localeNames[] = getLocale.value();

		for (String localeName : localeNames) {
			String localeValue = webRequest.getHeader(localeName);
			if (localeValue != null && !localeValue.isEmpty()) {
				Locale locale = Locale.forLanguageTag(localeValue);
				if (locale != null) {
					return locale.getLanguage();
				}
			}
		}
		
		if (getLocale.p()) {
			for (String localeName : localeNames) {
				String localeValue = webRequest.getParameter(localeName);
				if (localeValue != null && !localeValue.isEmpty()) {
					Locale locale = Locale.forLanguageTag(localeValue);
					if (locale != null) {
						return locale.getLanguage();
					}
				}
			}
		}

		return null;
	}

}
